package com.exsun.ex1077.network

import com.franmontiel.persistentcookiejar.PersistentCookieJar
import com.franmontiel.persistentcookiejar.cache.SetCookieCache
import com.franmontiel.persistentcookiejar.persistence.SharedPrefsCookiePersistor
import com.zhangping.fastjetpack.base.appContext
import com.zhangping.fastjetpack.network.BaseNetworkApi
import com.zhangping.fastjetpack.network.gson.GsonUtils
import com.zhangping.fastjetpack.network.interceptor.logging.LogInterceptor
import okhttp3.Cache
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.io.File
import java.util.concurrent.TimeUnit

/**
 * 描述：API请求构造器
 * 作者：ZhangPing
 * 创建时间：2022/2/23 21:34
 */
val apiService by lazy {
    NetworkApi.INSTANCE.getApi(ApiService::class.java, NetworkApi.url)
}
class NetworkApi : BaseNetworkApi(){

    companion object{
        const val url = ApiUrl.BASE_URL
        val INSTANCE by lazy { NetworkApi() }
    }

    override fun setHttpClientBuilder(builder: OkHttpClient.Builder): OkHttpClient.Builder {
        return builder.apply {
            //设置最大缓存10M
            cache(Cache(File(appContext.cacheDir, "appCache"), 10 * 1024 * 1024))
            //设置cookie自动持久化
            cookieJar(cookieJar)
            //设置请求头Token
            addInterceptor(TokenHeader())
            //设置日志拦截器
            addInterceptor(LogInterceptor())
            //设置连接、读、写超时时间
            connectTimeout(10, TimeUnit.SECONDS)
            readTimeout(10, TimeUnit.SECONDS)
            writeTimeout(10, TimeUnit.SECONDS)
        }
    }

    override fun setRetrofitBuilder(builder: Retrofit.Builder): Retrofit.Builder {
        return builder.addConverterFactory(GsonConverterFactory.create(GsonUtils.fixGson()))
    }

    private val cookieJar : PersistentCookieJar by lazy {
        PersistentCookieJar(SetCookieCache(), SharedPrefsCookiePersistor(appContext))
    }
}